<template>
  <div>
    <el-card class="search-box">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用户名">
              <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="专业">
              <el-input v-model="form.major" placeholder="请输入专业"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="院系">
              <el-input v-model="form.department" placeholder="请输入院系"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="籍贯">
              <el-input v-model="form.nativePlace" placeholder="请输入籍贯"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电话">
              <el-input v-model="form.phone" placeholder="请输入电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮箱">
              <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-box">
      <el-table :data="alumnus" border stripe v-loading="loading" style="width: 100%;height: 100%;">
        <!-- 姓名 -->
        <el-table-column prop="name" label="姓名" width="80" fixed="left"></el-table-column>
        <!-- 用户名 -->
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="password" label="密码" width="120"></el-table-column>
        <!-- 头像（自定义显示） -->
        <el-table-column prop="image" label="头像" width="120">
          <template v-slot="{ row }">
            <el-image style="width: 80px; height: 50px" :src="row.image"
              :preview-src-list="row.image ? [row.image] : []" fit="cover" hide-on-click-modal>
              <template #error>
                <div class="image-placeholder">
                  <i class="el-icon-user-solid"></i>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <!-- 性别（格式化显示） -->
        <el-table-column prop="gender" label="性别" width="80" :formatter="genderFormatter"></el-table-column>
        <!-- 入学时间 -->
        <el-table-column prop="enrollmentDate" label="入学时间" width="100" :formatter="dateFormatter"></el-table-column>
        <!-- 毕业时间 -->
        <el-table-column prop="graduationDate" label="毕业时间" width="100" :formatter="dateFormatter"></el-table-column>
        <!-- 专业 -->
        <el-table-column prop="major" label="专业" width="150"></el-table-column>
        <!-- 院系 -->
        <el-table-column prop="department" label="院系" width="150"></el-table-column>
        <!-- 籍贯 -->
        <el-table-column prop="nativePlace" label="籍贯" width="150"></el-table-column>
        <!-- 电话 -->
        <el-table-column prop="phoneNumber" label="电话" width="150"></el-table-column>
        <!-- 邮箱 -->
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <!-- 创建时间 -->
        <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
        <!-- 最后操作时间 -->
        <el-table-column prop="updateTime" label="最后操作时间" width="160"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template v-slot="{ row }">
            <div class="action-cell">
              <el-checkbox v-model="row.selected" />
              <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.current" :page-sizes="[5, 10, 20, 50]" :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
      </el-pagination>
      <div class="action-buttons">
        <el-button type="danger" @click="handleDeleteSelected">删除选中</el-button>
        <el-button type="primary" class="publish-btn" @click="handleAdd">添加校友</el-button>
      </div>
    </el-card>

    <!-- 编辑个人信息组件 -->
    <el-dialog title="编辑校友信息" :visible.sync="editDialogVisible" width="600px" @close="handleClose">
      <el-form ref="editForm" :model="editForm" :rules="rules" label-width="100px" label-position="right">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input v-model="editForm.checkPassword" type="password" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入学时间" prop="enrollmentDate">
          <el-date-picker v-model="editForm.enrollmentDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="毕业时间" prop="graduationDate">
          <el-date-picker v-model="editForm.graduationDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="专业" prop="major">
          <el-input v-model="editForm.major" clearable></el-input>
        </el-form-item>

        <el-form-item label="院系" prop="department">
          <el-input v-model="editForm.department" clearable></el-input>
        </el-form-item>

        <el-form-item label="籍贯" prop="nativePlace">
          <el-input v-model="editForm.nativePlace" clearable></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="editForm.phoneNumber" clearable></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加校友 -->
    <el-dialog title="添加校友信息" :visible.sync="addDialogVisible" width="600px" @close="handleCloseAdd">
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="100px" label-position="right">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addForm.gender" placeholder="请选择">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入学时间" prop="enrollmentDate">
          <el-date-picker v-model="addForm.enrollmentDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="毕业时间" prop="graduationDate">
          <el-date-picker v-model="addForm.graduationDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker v-model="addForm.birthDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="专业" prop="major">
          <el-input v-model="addForm.major" clearable></el-input>
        </el-form-item>

        <el-form-item label="院系" prop="department">
          <el-input v-model="addForm.department" clearable></el-input>
        </el-form-item>

        <el-form-item label="籍贯" prop="nativePlace">
          <el-input v-model="addForm.nativePlace" clearable></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="addForm.phoneNumber" clearable></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import dayjs from 'dayjs';
import service from '@/utils/request';
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      addDialogVisible: false,
      addForm: {
        name: '',
        username: '',
        password: '',
        checkPassword: '',
        gender: '',
        enrollmentDate: '',
        graduationDate: '',
        birthDate: '',
        major: '',
        department: '',
        nativePlace: '',
        phoneNumber: '',
        email: ''
      },

      loading: false,
      form: {
        id: '',
        name: '',
        username: '',
        gender: '',
        major: '',
        department: '',
        nativePlace: '',
        phone: '',
        email: ''
      },

      alumnus: [],
      pagination: {
        current: 1,
        size: 5,
        total: 0
      },

      // 编辑表单
      editDialogVisible: false,
      editForm: {
        name: '',
        username: '',
        password: '',
        checkPassword: '',
        gender: '',
        enrollmentDate: '',
        graduationDate: '',
        major: '',
        department: '',
        nativePlace: '',
        phoneNumber: '',
        email: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        enrollmentDate: [
          { required: true, message: '请选择入学日期', trigger: 'change' } // 移除type检查
        ],
        graduationDate: [
          { required: true, message: '请选择毕业日期', trigger: 'change' } // 移除type检查
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    //获取数据
    async fetchData() {
      try {
        this.loading = true;
        const params = {
          ...this.form,
          page: this.pagination.current,
          pageSize: this.pagination.size
        };

        const response = await service.get('/Admin/Alumnus', { params })

        // 处理分页数据
        this.alumnus = response.rows
        this.pagination.total = response.total

      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('网络请求异常');

      } finally {
        this.loading = false;
      }
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size;
      this.fetchData();
    },

    // 当前页码变化
    handleCurrentChange(current) {
      this.pagination.current = current;
      this.fetchData();
    },

    // 查询操作
    handleSearch() {
      this.pagination.current = 1;
      this.fetchData();
    },

    // 重置表单
    handleReset() {
      this.$refs.form.resetFields();
      this.handleSearch();
    },
    // 性别格式化
    genderFormatter(row) {
      return row.gender == '1' ? '男' : '女'
    },
    handleAdd() {
      this.addDialogVisible = true;
    },
    // 编辑信息
    handleEdit(row) {
      this.editDialogVisible = true;
      // 深拷贝数据
      this.editForm = {
        ...row,
        checkPassword: row.password,
        enrollmentDate: this.formatDate(row.enrollmentDate),
        graduationDate: this.formatDate(row.graduationDate)
      };
    },
    submitForm() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          try {
            const postData = {
              ...this.editForm,
              enrollmentDate: dayjs(this.editForm.enrollmentDate).format("YYYY-MM-DD"),
              graduationDate: dayjs(this.editForm.graduationDate).format("YYYY-MM-DD"),
              checkPassword: undefined
            };

            const res = await service.put("http://localhost:8080/Admin/Alumnus/Update", postData);

            if (res.code == 1) {
              this.$message.success('更新成功');
              this.addDialogVisible = false;
              this.fetchData(); // 刷新表格数据
            }
          } catch (error) {
            this.$message.error('更新失败');
          }
        }
      });
    },
    submitAddForm() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          try {
            const postData = {
              ...this.addForm,
              enrollmentDate: dayjs(this.addForm.enrollmentDate).format("YYYY-MM-DD"),
              graduationDate: dayjs(this.addForm.graduationDate).format("YYYY-MM-DD"),
              birthDay: dayjs(this.addForm.birthDay).format("YYYY-MM-DD"),
              checkPassword: undefined
            };

            const res = await service.post("http://localhost:8080/Admin/Alumnus/Add", postData);

            if (res.code == 1) {
              this.$message.success('添加成功');
              this.addDialogVisible = false;
              this.fetchData(); // 刷新表格数据
            }
          } catch (error) {
            this.$message.error('更新失败');
          }
        }
      });
    },
    // 新增方法 - 删除选中
    async handleDeleteSelected() {
      const selectedIds = this.alumnus
        .filter(item => item.selected)
        .map(item => item.id);

      if (selectedIds.length === 0) {
        this.$message.warning('请选择要删除的校友');
        return;
      }

      try {
        await this.$confirm('确定删除选中的校友吗？', '提示', {
          type: 'warning'
        });

        const res = await service.post('http://localhost:8080/Admin/Alumnus/Delete',selectedIds,{
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

        if (res.code === 1) {
          this.$message.success('删除成功');
          this.fetchData();
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    handleClose() {
      this.$refs.editForm.resetFields();
    },
    handleCloseAdd() {
      this.$refs.addForm.resetFields();
    },

    // 日期格式化方法
    formatDate(timestamp) {
      if (!timestamp) return '';
      return dayjs(timestamp).format('YYYY-MM-DD');
    },
    dateFormatter(row, column, cellValue) {
      return this.formatDate(cellValue);
    }
  }
};
</script>

<style scoped>
.search-box {
  width: 100%;
  height: 100%;
}
</style>